from flask import Blueprint, request, jsonify
from werkzeug.exceptions import BadRequest, Conflict, Forbidden
from app import db
from app.auth.models import User, UserFollows
from .schemas import user_profile_schema, user_with_recipes_schema, users_schema
from flask import Blueprint, request, jsonify

# 创建用户模块的蓝图
users_bp = Blueprint('users', __name__)

@users_bp.route('/', methods=['GET'])
def get_users():
    """
    获取所有用户列表
    ---
    响应：用户列表
    """
    users = User.query.all()
    return jsonify(users_schema.dump(users))

@users_bp.route('/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """
    获取单个用户的详细信息
    ---
    参数：user_id - 用户ID
    响应：用户详细信息
    """
    user = User.query.get_or_404(user_id)
    return jsonify(user_profile_schema.dump(user))

@users_bp.route('/profile', methods=['GET'])
def get_user_profile():
    """
    获取当前用户的个人资料
    ---
    参数：user_id - 用户ID
    响应：用户资料
    """
    user_id = request.args.get('user_id')
    if not user_id:
        raise BadRequest('Missing user ID')
    user = User.query.get_or_404(user_id)
    return jsonify(user_profile_schema.dump(user)), 200

@users_bp.route('/profile', methods=['PUT'])
def update_user_profile():
    """
    更新用户资料
    ---
    参数：user_id - 用户ID
    请求体：更新的用户资料
    响应：更新后的用户资料
    """
    data = request.get_json()
    
    if not data:
        raise BadRequest('No input data provided')
    
    user_id = request.args.get('user_id')
    if not user_id:
        raise BadRequest('Missing user ID')
    user = User.query.get_or_404(user_id)
    
    # 更新用户资料（只更新请求中提供的字段）
    if 'username' in data:
        # 检查用户名是否已存在
        if User.query.filter_by(username=data['username']).first() and data['username'] != user.username:
            raise BadRequest('Username already exists')
        user.username = data['username']
    if 'email' in data:
        # 检查邮箱是否已存在
        if User.query.filter_by(email=data['email']).first() and data['email'] != user.email:
            raise BadRequest('Email already exists')
        user.email = data['email']
    if 'phone' in data: user.phone = data['phone']
    if 'address' in data: user.address = data['address']
    if 'avatar' in data: user.avatar = data['avatar']
    
    db.session.commit()
    return jsonify(user_profile_schema.dump(user)), 200

@users_bp.route('/<int:user_id>/recipes', methods=['GET'])
def get_user_recipes(user_id):
    """
    获取指定用户创建的所有食谱
    ---
    参数：user_id - 用户ID
    响应：用户的食谱列表
    """
    user = User.query.get_or_404(user_id)
    return jsonify(user_with_recipes_schema.dump(user))

@users_bp.route('/<int:user_id>/favorites', methods=['GET'])
def get_user_favorites(user_id):
    """
    获取指定用户收藏的所有食谱
    ---
    参数：user_id - 用户ID
    响应：用户收藏的食谱列表
    """
    from app.favorites.schemas import favorites_schema
    user = User.query.get_or_404(user_id)
    return jsonify(favorites_schema.dump(user.favorites))

@users_bp.route('/search', methods=['GET'])
def search_users():
    """
    搜索用户
    ---
    参数：q - 搜索关键词
    响应：匹配的用户列表
    """
    keyword = request.args.get('q', '')
    if not keyword:
        return jsonify(users_schema.dump([]))
    
    users = User.query.filter(
        User.username.contains(keyword)
    ).all()
    
    return jsonify(users_schema.dump(users))

@users_bp.route('/<int:followed_id>/follow', methods=['POST'])
def follow_user(followed_id):
    """
    关注用户
    ---
    参数：followed_id - 被关注用户ID
    请求体：follower_id - 粉丝用户ID
    响应：关注关系信息
    """
    data = request.get_json()
    if not data or 'follower_id' not in data:
        raise BadRequest('Missing follower ID')
        
    follower_id = data['follower_id']
    
    # 检查不能关注自己
    if follower_id == followed_id:
        raise Forbidden('Cannot follow yourself')
        
    # 检查用户是否存在
    follower = User.query.get_or_404(follower_id)
    followed = User.query.get_or_404(followed_id)
    
    # 检查是否已经关注
    existing_follow = UserFollows.query.filter_by(
        follower_id=follower_id,
        followed_id=followed_id
    ).first()
    
    if existing_follow:
        raise Conflict('Already following this user')
        
    # 创建新的关注关系
    new_follow = UserFollows(
        follower_id=follower_id,
        followed_id=followed_id
    )
    
    db.session.add(new_follow)
    db.session.commit()
    
    return jsonify({
        'message': 'Successfully followed user',
        'follow_id': new_follow.id
    }), 201

@users_bp.route('/<int:followed_id>/unfollow', methods=['DELETE'])
def unfollow_user(followed_id):
    """
    取消关注用户
    ---
    参数：followed_id - 被关注用户ID
    请求体：follower_id - 粉丝用户ID
    响应：成功消息
    """
    data = request.get_json()
    if not data or 'follower_id' not in data:
        raise BadRequest('Missing follower ID')
        
    follower_id = data['follower_id']
    
    # 检查用户是否存在
    follower = User.query.get_or_404(follower_id)
    followed = User.query.get_or_404(followed_id)
    
    # 查找关注关系
    follow = UserFollows.query.filter_by(
        follower_id=follower_id,
        followed_id=followed_id
    ).first()
    
    if not follow:
        raise BadRequest('Not following this user')
        
    # 删除关注关系
    db.session.delete(follow)
    db.session.commit()
    
    return jsonify({'message': 'Successfully unfollowed user'}), 200

@users_bp.route('/<int:user_id>/following', methods=['GET'])
def get_user_following(user_id):
    """
    获取用户关注列表
    ---
    参数：user_id - 用户ID
    响应：用户关注的用户列表
    """
    user = User.query.get_or_404(user_id)
    
    # 分页参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    # 查询用户关注的人并分页
    following_users = User.query.join(
        UserFollows, User.id == UserFollows.followed_id
    ).filter(
        UserFollows.follower_id == user_id
    ).paginate(page=page, per_page=per_page, error_out=False)
    
    return jsonify({
        'users': users_schema.dump(following_users.items),
        'total': following_users.total,
        'page': page,
        'per_page': per_page,
        'pages': following_users.pages
    })

def get_user_id_by_username(username):
    """
    通过用户名获取用户ID
    """
    user = User.query.filter_by(username=username).first()
    if not user:
        raise BadRequest(f'User with username {username} not found')
    return user.id

@users_bp.route('/<int:user_id>/followers', methods=['GET'])
def get_user_followers(user_id):
    """
    获取用户粉丝列表
    ---
    参数：user_id - 用户ID
    响应：用户的粉丝列表
    """
    user = User.query.get_or_404(user_id)
    
    # 分页参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    # 查询用户的粉丝并分页
    follower_users = User.query.join(
        UserFollows, User.id == UserFollows.follower_id
    ).filter(
        UserFollows.followed_id == user_id
    ).paginate(page=page, per_page=per_page, error_out=False)
    
    return jsonify({
        'users': users_schema.dump(follower_users.items),
        'total': follower_users.total,
        'page': page,
        'per_page': per_page,
        'pages': follower_users.pages
    })

@users_bp.route('/username/<string:username>/followers', methods=['GET'])
def get_user_followers_by_username(username):
    """
    通过用户名获取用户粉丝列表
    ---
    参数：username - 用户名
    响应：用户的粉丝列表
    """
    user_id = get_user_id_by_username(username)
    return get_user_followers(user_id)